package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.UserLoginService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.awt.geom.QuadCurve2D;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {


    @Override
    public ResponseResult login(AdUserDto dto) {

        //1:校验参数
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名或密码不能为空");
        }

        //2：数据库查用户是否合法
        Wrapper wrapper =new QueryWrapper<AdUser>();
        ((QueryWrapper) wrapper).eq("name",dto.getName());

//        LambdaQueryWrapper wrapper1 =new LambdaQueryWrapper();
//        wrapper1.eq("name",dto.getName());
//
//        QueryWrapper queryWrapper =new QueryWrapper();
//        queryWrapper.lambda().eq("name",dto.getName());

        List<AdUser> userList = this.list(wrapper);  //查询出用户信息
        if(userList !=null && userList.size()==1){
            AdUser adUser = userList.get(0);

            //根据查询的用户密码 +库中的盐值 生成一个新的加密密码串，比较
            String salt = adUser.getSalt();
            String pwdSalt = dto.getPassword()+salt;

            String newPwd = DigestUtils.md5DigestAsHex(pwdSalt.getBytes());
            if(newPwd.equals(adUser.getPassword())){
                //用户密码是输入对的    //3:生成token jwt
                Map<String, Object> map =new HashMap<>();
                adUser.setPassword("");
                adUser.setSalt("");
                map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));  //生成token 包含用户的id
                map.put("user",adUser);

                //4:把token 返回前端
                return ResponseResult.okResult(map);
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
    }
}

